package com.dhms.vostok1.utils

import android.content.Context
import android.util.Log
import android.util.TypedValue
import android.widget.EditText
import androidx.annotation.AttrRes
import androidx.annotation.ColorInt
import com.dhms.vostok1.network.MoshiObject
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.*

//"2006-01-02 15:04:05"
fun String.toDate(format: String = "yy-MM-dd HH:mm:ss"): Date? {
    return try {
        SimpleDateFormat(format, Locale.CHINA).parse(this, ParsePosition(0))
    } catch (e: Exception) {
        Log.e("Time", "$this, $e")
        null
    }
}

fun Date.secondTimeStamp(): Long {
    return time / 1000
}

fun Date.toFormatDate(format: String = "yy-MM-dd HH:mm:ss"): String {
    return SimpleDateFormat(format, Locale.CHINA).format(this)
}

fun EditText.isEndIconVisible(hasFocus: Boolean): Boolean {
    return hasFocus && this.text.isNotEmpty()
}

@ColorInt
fun Context.getColorFromAttr(
    @AttrRes attrColor: Int,
    typedValue: TypedValue = TypedValue(),
    resolveRefs: Boolean = true
): Int {
    theme.resolveAttribute(attrColor, typedValue, resolveRefs)

    return typedValue.data
}

inline fun <reified T> T.toMap(): Map<String, String>? {
    val objectString = MoshiObject.moshi.adapter(T::class.java).toJson(this)
    return MoshiObject.jsonAdapterToMapString.fromJson(objectString)
}

inline fun <reified T> T.toAnyMap(): Map<String, Any>? {
    val objectString = MoshiObject.moshi.adapter(T::class.java).toJson(this)
    return MoshiObject.jsonAdapterToMapAny.fromJson(objectString)
}

fun <T : Number> getLongValue(vararg any: T): Long {
    return any.first().toLong()
}